package com.xiaoying.server.publish.upload;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.BlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xiaoying.server.publish.comomon.upyun.UpYunUtil;
import com.xiaoying.server.publish.entity.FileInfo;
import com.xiaoying.server.publish.entity.UploadResult;
import com.xiaoying.server.publish.utils.DateUtil;
import com.xiaoying.server.publish.utils.RandomUtil;



public class UploadFile {
	private static Log log = LogFactory.getFactory().getInstance(UploadFile.class);
	
	
    /**
     * 上传文件函数
     * @param fileUploadQueue 请求待传队列
     * @throws IOException
     * @throws JMSException
     * @throws InterruptedException
     * @author ZJD
     */
	public static UploadResult upload(final BlockingQueue<FileInfo> fileUploadQueue,
			final BlockingQueue<UploadResult> uploadResultQueue,final FileInfo fileInfo) {
		// 上传次数增加1
		fileInfo.setUploadCount(fileInfo.getUploadCount()+1);
		UploadResult uploadResult = new UploadResult(fileInfo);	
		// 本地拼接远端的文件夹路径 路径dir 2013/0510/1105/[文件类型][FUID].[文件后缀名]
		String dir = UpYunUtil.DIR_TEST+DateUtil.getDirByDate(new Date());
		try {
			// 创建路径,上传文件
			if(UpYunUtil.MkDir(dir,fileInfo.getFileType())){
				// 构建上传upYun上的远端路径
				String remotePath = dir+"/"+fileInfo.getFileType()
								+RandomUtil.get3FileName()+fileInfo.getFileSuffix();
				uploadResult.setRemotePath(remotePath);	
				uploadResult.setUploadDt(DateUtil.getDateTimeByFormat(new Date()));
				if(!UpYunUtil.upLoadFile(remotePath,
						new File(fileInfo.getFilePath()),fileInfo.getFileType())){
					// 文件上传失败处理
					log.error("上传文件失败! ["+ fileInfo.getFilePath()+"]");
					uploadResult.setResultType(UploadResult.TYPE_FAIL);
				}else{
					// 上传成功,测试显示路径
					log.debug("完成"+fileInfo.getId()+"文件的上传");
				}// end if
			}else{
				fileUploadQueue.add(fileInfo);
				log.debug("创建remote路径失败");
			}// end if
		} catch (IOException e) {
//			threadStatus = false;
			log.error("上传文件失败: "+e);
		} finally{
//			if(!threadStatus){
//				this.setStatus(UploadFileManager.STATUS_DEAD);
//			}
		}
//		this.setStatus(UploadFileManager.STATUS_ACTIVE);
		return uploadResult;
	}
	
	
}
